#include "stdafx.h"
#include "./strutils.h"

void StrUtils::WideStringToUTF8String(const wstring& in, string& out)
{
	int len = (int)in.length();
	char* pBuf = new char[len * 3 + 1];
	memset(pBuf, 0, len * 3 + 1);
#ifdef _WINDOWS
	::WideCharToMultiByte(CP_UTF8, 0, in.c_str(), len, pBuf, len * 3, NULL, NULL);
#elif defined _UNIX
	iconv_t env;
	env = iconv_open("UTF-8","wchar_t");
	iconv(env, (char**)&in.c_str(), (size_t*)&len * sizeof(wchar_t), (char**)&pBuf, (size_t*)&len * 3);
	iconv_close(env);
#endif
	out = pBuf;
	delete [] pBuf;
}


void StrUtils::UTF8StringToWideString(const string& in, wstring& out)
{
	int len = (int)in.length();
	wchar_t* pBuf = new wchar_t[len + 1];
	memset(pBuf, 0, (len + 1) * sizeof(wchar_t));
#ifdef _WINDOWS
	::MultiByteToWideChar(CP_UTF8, 0, in.c_str(), len, pBuf, len * sizeof(wchar_t));
#elif defined _UNIX
	iconv_t env;
	env = iconv_open("wchar_t","UTF-8");
	iconv(env, (char**)&in.c_str(), (size_t*)&len, (char**)&pBuf, (size_t*)&len * sizeof(wchar_t));
	iconv_close(env);
#endif
	out = pBuf;
	delete [] pBuf;
}

void StrUtils::UTF8Encode(const wstring& in, string& out)
{
	WideStringToUTF8String(in, out);
}

void StrUtils::UTF8Decode(const string& in, wstring& out)
{
	UTF8StringToWideString(in, out);
}

string StrUtils::IntToString(int num)
{
	static char buf[256];
	sprintf_s(buf, 256, "%d", num);

	return buf;
}